<template>
  <j-modal :title="title" :width="width" :visible="visible" switchFullscreen @cancel="handleCancel">

    <template #footer>
      <a-button key="1" @click="handleCancel">关闭</a-button>
      <a-button
        :hidden="disableSubmit"
        v-if="!onlyLook"
        key="2"
        type="primary"
        :loading="loading"
        @click="saveTo">签发</a-button>
      <a-button
        :hidden="disableSubmit"
        v-if="onlyLook && progress!=&quot;1&quot;"
        key="3"
        type="primary"
        :loading="loading"
        @click="saveFeedback">保存</a-button>
    </template>

    <div class="notice-publish-content">
      <div class="top-area">
        <div>
          <a-switch
            v-show="onlyLook && userInfo().username==createBy"
            checked-children="公开"
            un-checked-children="隐藏"
            v-model="ischecked"
            @change="swichChange"
            v-has="'publishCollectHiddenBtns'" />

          <a-switch
            v-show="onlyLook"
            checked-children="公开"
            un-checked-children="隐藏"
            v-model="ischecked"
            @change="swichChange"
            v-has="'publishCollectHiddenBtn'" />

        </div>
        <div class="r-area">

          <a-button key="1" @click="readSituation" type="primary">阅读情况</a-button>
          <a-button
            key="2"
            style="margin-left: 10px"
            @click="signOpinion"
            type="primary"
            v-has="'publishCollectSignOpinionBtn'">签发意见</a-button>

        </div>

      </div>

      <div class="title">{{ model.title }}</div>
      <div class="pub-name-time">
        <span>发布人：{{ model.handlerId_dictText }}</span>
        <span>发布时间：{{ model.publishTime }}</span>
        <span>意见收集人：{{ model.collectorEmpId_dictText }}</span>

      </div>
      <a-card class="person-card">
        <opinionForm ref="realForm" :disabled="true" />
      </a-card>

      <a-card class="person-card" v-if="hingerOpinionList.length!==0">
        <p class="top-txt">上级签发意见：</p>
        <p v-for="(item,index) in hingerOpinionList" :key="index">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.empId_dictText }}：{{ item.opinion }}&nbsp;&nbsp; {{
            item.timeIssue }}
        </p>
      </a-card>
      <a-card class="person-card" v-if="lowerOpinionList.length!==0">
        <p class="top-txt">下级签发意见：</p>
        <p v-for="(item,index) in lowerOpinionList" :key="index">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.empId_dictText }}：{{ item.opinion }}&nbsp;&nbsp; {{
            item.timeIssue }}
        </p>
      </a-card>

      <a-card class="person-card" v-show="userInfo().username==createBy" v-has="&quot;publishCollectOpinionBtns&quot;">
        <a-button type="primary" @click="collectDownLoad">征集意见</a-button>
      </a-card>
      <a-card class="person-card" v-show="userInfo().username!==createBy && userInfo().empId==collectorEmpId">
        <a-button type="primary" @click="collectDownLoad">征集意见</a-button>
      </a-card>
      <a-card
        class="person-card"
        v-show="userInfo().username!==createBy && userInfo().empId!==collectorEmpId"
        v-has="&quot;publishCollectOpinionBtn&quot;">
        <a-button type="primary" @click="collectDownLoad">征集意见</a-button>
      </a-card>
      <a-card
        class="person-card"
        v-show="userInfo().username==createBy && userInfo().empId!==collectorEmpId"
        v-has="&quot;publishCollectOpinionBtn&quot;">
        <a-button type="primary" @click="collectDownLoad">征集意见</a-button>
      </a-card>
      <a-card
        class="person-card"
        v-show="userInfo().username==createBy && userInfo().empId==collectorEmpId"
        v-has="&quot;publishCollectOpinionBtn&quot;">
        <a-button type="primary" @click="collectDownLoad">征集意见</a-button>
      </a-card>

      <a-card class="person-card" :tab-list="tabList" active-tab-key="1" v-if="!onlyLook">
        <div class="flex">
          <div class="flex" style="width:50%">
            <div style="width:145px">签发意见：</div>
            <a-textarea
              v-model="opinionValue"
              :maxLength="500"
              placeholder="（签发部门）示例：请**部门/人于**月**日前完成**工作。
（被签发部门）示例：已于**月**日完成***工作，请知悉。
"
              :rows="4" />
          </div>
          <div class="flex" style="width:50%;margin-left:20px;">
            <p style="width:100px">签发接收人：</p>
            <a-button type="primary" @click="acceptClick">{{ selectEmpList.length==0?'未选择':'已选择' }}</a-button>
          </div>
        </div>
        <div class="flex">
          <p>本级反馈意见：</p>
          <a-textarea v-model="feedbackOpinion" :maxLength="500" placeholder="请输入" :rows="4" />
        </div>

      </a-card>

      <a-card class="person-card" :tab-list="tabList1" active-tab-key="1" v-if="onlyLook && progress!=&quot;1&quot;">
        <div class="flex">
          <p>反馈意见：</p>
          <a-textarea v-model="feedbackOpinion" :disabled="timeDisable" :maxLength="500" placeholder="请输入" :rows="4" />
        </div>
      </a-card>

    </div>
    <teamChoose
      ref="team"
      @sure="sureTeam"
      :selectEmpList="selectEmpList"
      :intensiveType="dataForm.intensiveType"
      formType="opinion"
      :publishId="publishId"
      :disabled="false" />
    <readSituationModal ref="read" :publishId="publishId" formType="opinion" />
    <signIssue ref="sign" :publishId="publishId" formType="opinion" />
    <collectIssue ref="collect" :publishId="publishId" formType="opinion" />
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { mapGetters } from 'vuex'
import teamChoose from '../comp/teamChooseModal'
import readSituationModal from '../comp/readSituationModal'
import signIssue from '../comp/signIssue'
import collectIssue from '../comp/collectIssue'
import opinionForm from './opinionForm'
import moment from 'moment'

export default {
  name: 'NoticeSignPublish',
  components: {
    teamChoose,
    readSituationModal,
    signIssue,
    collectIssue,
    opinionForm
  },
  data () {
    return {
      isProxy: false, // 是否是代理人签发
      tabList: [{
        key: '1',
        tab: '签发栏'
      }],
      tabList1: [{
        key: '1',
        tab: '意见反馈'
      }],
      title: '',
      progress: '',
      progress_dictText: '',
      model: {},
      dataForm: {},
      width: 1400,
      visible: false,
      disableSubmit: false,
      loading: false,
      queryPageById: '/api/erp/publishCollect/queryPageById', // 获取详情
      hingerOpinionListUrl: '/api/erp/publishCollect/emp/hingerOpinionList', // 查当前人员上级签发意见
      hingerLowerListUrl: '/api/erp/publishCollect/emp/hingerLowerList', // 查当前人员下级签发意见
      signEmp: '/api/erp/publishCollect/signEmp', // 签发
      feedbackUrl: '/api/erp/publishCollect/feedback', // 反馈意见
      signEmpProxy: '/api/erp/publishCollect/signEmpProxy', // 代理签发
      readUrl: '/api/erp/publishCollect/read',
      findEmpUserSelect: '/api/erp/publishCollect/findEmpUserSelect',
      selectEmpList: [], // 签发接收人
      opinionValue: '', // 签发意见value
      feedbackOpinion: '', // 本级反馈意见
      hingerOpinionList: [], // 上级签发意见list
      lowerOpinionList: [], // 下级意见list
      publishId: '',
      onlyLook: false,
      ischecked: '',
      collectorEmpId: '',
      createBy: ''
    }
  },
  computed: {
    // 判断当前时间是否大于截止时间，大于则结束填写签发意见
    timeDisable () {
      // 判断当前时间是否已经超过截止时间，如果超过则不能填写反馈意见
        if (this.model.blockingTime && moment(this.model.blockingTime).isBefore(moment())) {
          return true
        } else {
          return false
        }
    }
  },
  methods: {
    ...mapGetters(['userInfo']),
    // 变为已读
    getToRead() {
        getAction(this.readUrl, {
          empId: this.userInfo().empId,
          collectId: this.publishId
        })
      },
    // 切换
    async swichChange(value) {
      let url = `/api/erp/publishCollect/${value ? 'open' : 'hidden'}`
      let res = await getAction(url, {
        collectId: this.publishId
      })
      if (res.success) {
        this.$message.success('操作成功！')
      }
    },
    async init (record, isLook) {
      this.onlyLook = !!isLook
      this.dataForm = Object.assign({}, record)
      this.visible = true
      this.title = isLook ? '查看' : '签发'
      this.opinionValue = ''
      this.selectEmpList = []
      this.createBy = record.createBy
      // 流程的进度
      // if(this.isProxy){
      //   this.progress = '1'
      // }else{
      //   this.progress = record.progress
      // }

      if (this.onlyLook && this.progress != '1') {
        this.feedbackOpinion = record.feedbackOpinion
      } else {
        this.feedbackOpinion = ''
      }

      this.progress = record.progress
      this.publishId = record.id
      this.progress_dictText = record.progress_dictText

      this.collectorEmpId = record.collectorEmpId

      this.$nextTick(() => {
        this.$refs.realForm.addOrEdit(record)
      })

      this.getSelectUsers(record.id)

      this.getToRead(record.id)

      let res = await getAction(this.queryPageById, { id: record.id })

      if (res.success) {
          this.model = res.result.records[0]
        }

        this.ischecked = this.model.hidden == '0'

      // 查当前人员上级签发意见
      let rr = await getAction(this.hingerOpinionListUrl, {
        empId: this.userInfo().empId,
        collectId: record.id
      })

      if (rr.success) {
        this.hingerOpinionList = rr.result.records || []
      }
      // 查当前人员下级签发意见
      let aa = await getAction(this.hingerLowerListUrl, {
        empId: this.userInfo().empId,
        collectId: record.id
      })

      if (aa.success) {
        this.lowerOpinionList = aa.result.records || []
      }
    },
    // 获取选中的接收人
    async getSelectUsers(id) {
      let progress = this.isProxy ? '1' : String(parseInt(this.progress) + 1)
      let params = {
          collectId: id,
          pageNo: 1,
          pageSize: -1,
          empId: this.userInfo().empId
        }
        let res = await getAction(this.findEmpUserSelect, params)
        if (res.success) {
          this.selectEmpList = res.result.records || []
        } else {
          this.selectEmpList = []
        }
    },
    // 阅读情况
    readSituation() {
      this.$refs.read.init()
    },
    // 签发意见
    signOpinion() {
      this.$refs.sign.init()
    },
    acceptClick() {
      this.$nextTick(() => {
        let progress = this.isProxy ? '1' : String(parseInt(this.progress) + 1)

        this.$refs.team.init(progress, this.progress_dictText)
      })
    },
    // 征集意见下载
    collectDownLoad() {
      this.$refs.collect.init()
    },
    // 确定选择
    sureTeam(selectList) {
      this.selectEmpList = selectList
    },
    async saveTo() {
      if (!this.opinionValue) {
        return this.$message.error('请输入签发意见！')
      }
      // if(this.selectEmpList.length===0){
      //   return this.$message.error('请选择签发人接收人！')
      // }

      if (!this.feedbackOpinion) {
        return this.$message.error('请输入本级的反馈意见！')
      }

      let selectEmpList = JSON.parse(JSON.stringify(this.selectEmpList))

      selectEmpList = selectEmpList.map(rr => {
        return {
          empId: rr.empId,
          empDepartIds: rr.departId,
          username: rr.username,
          realname: rr.realname
        }
      })
      this.loading = true
       // 是否是代理签发
       let url = this.isProxy ? this.signEmpProxy : this.signEmp
      // 签发保存
      let res = await postAction(url, {
        empId: this.userInfo().empId,
        id: this.model.id,
        opinion: this.opinionValue,
        feedbackOpinion: this.feedbackOpinion,
        selectEmpList,
        timeIssue: moment().format('YYYY-MM-DD HH:mm')
      })

      if (res.success) {
        this.$emit('ok')
        this.visible = false
        this.$message.success('签发成功')
      } else {
        this.$message.error(res.message || '操作失败！')
      }
      this.loading = false
    },
    // 保存反馈意见
    async saveFeedback() {
      if (!this.feedbackOpinion) {
        return this.$message.error('请输入反馈意见！')
      }
      let nowDateVeri = moment().format('YYYY-MM-DD HH:mm')
      if (moment(this.model.blockingTime).isBefore(nowDateVeri)) {
          return this.$message.error('已到期无法继续进行意见反馈！')
        }

      this.loading = true
      let res = await postAction(this.feedbackUrl, {
        empId: this.userInfo().empId,
        id: this.model.id,
        feedbackOpinion: this.feedbackOpinion
      })

      if (res.success) {
        this.$emit('ok')
        this.visible = false
        this.$message.success('保存成功')
      } else {
        this.$message.error(res.message || '操作失败！')
      }
      this.loading = false
    },
    handleCancel () {
      this.$emit('close')
      this.visible = false
    }
  }
}
</script>
<style lang='less' scoped>

.notice-publish-content {
  .top-area{
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .r-area{
      width: 20%;
      display: flex;
    }
  }

  .title {
    font-size: 30px;
    font-weight: 600;
    color:#000000;
    text-align: center;
  }
  .pub-name-time {
    margin: 20px 0px 0px 185px;
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
  }
  .person-card {
    width: 100%;
    margin-top: 20px;
    font-size: 16px;
    .top-txt{
      font-size: 16px;
      font-weight: 600;
    }
  }
  .flex {
    display: flex;
    align-items: center;
    margin-top: 20px;
    p {
      width: 10%;

    }
  }
}

</style>
